import { WarehouseDTO, AreaDTO, SiteDTO } from './../../../shared/service-proxy/service-proxies';
import { Component, OnInit, ViewChild, ElementRef, Injector } from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators
} from '@angular/forms';

import { loadModules } from 'esri-loader';
import esri = __esri;
import { ServiceProxy } from '@shared/service-proxy/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Router } from '@angular/router';
import { AppConsts } from "@shared/AppConsts";

@Component({
  selector: 'app-area-create',
  templateUrl: './area-create.component.html',
  styleUrls: ['./area-create.component.less']
})
export class AreaCreateComponent extends AppComponentBase implements OnInit {
  @ViewChild('mapViewNode') private mapViewEl: ElementRef;

  companyList: WarehouseDTO[] = [];
  checkStatusList = [];
  legendShow: boolean = false;
  sites: SiteDTO[] = [];

  radioValue = 'A';
  validateForm: FormGroup;
  area: AreaDTO;

  constructor(injector: Injector,
    private router: Router,
    private fb: FormBuilder,
    private _service: ServiceProxy) {
    super(injector);
  }

  getAllWarehouse() {
    this._service.getAllBySiteIdWarehouseDTOsUsingGET().subscribe(result => {
      this.companyList = result.result.fieldList;
    })
  }

  getSites() {
    this._service.getAllSitesBySiteUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
    })

  }
  changeSite() {
    const site = this.sites.find(m => m.id == this.area.siteId);
    if (site) {
      this.area.longitude = site.lng;
      this.area.latitude = site.lat;
      this.initializeMap();
    }

  }

  async initializeMap() {
    try {
      const [Map, MapView, Graphic, ScaleBar, TileLayer, Circle] = await loadModules([
        'esri/Map',
        'esri/views/MapView',
        'esri/widgets/ScaleBar',
        'esri/layers/TileLayer',
        'esri/Graphic',
        'esri/geometry/Circle',
        'dojo/domReady!'
      ], {
        url: AppConsts.arcgisMapUrl,         css: AppConsts.arcgisStyleUrl
      });

      // Set type of map
      const mapProperties: esri.MapProperties = {
        // basemap: this._basemap,
        layers: new TileLayer({
          url: AppConsts.arcgisMapServerUrl
        })
      };

      const map: esri.Map = new Map(mapProperties);
      if (this.area.id) {
        this._center = [this.area.longitude, this.area.latitude];
      }

      // Set type of map view
      const mapViewProperties: esri.MapViewProperties = {
        container: this.mapViewEl.nativeElement,
        center: this._center,
        zoom: this._zoom,
        map: map
      };

      const mapView: esri.MapView = new MapView(mapViewProperties);
      const parentThis = this.area;
      // All resources in the MapView and the map have loaded.
      // Now execute additional processes
      mapView.when(() => {
        const scaleBar = new ScaleBar({
          view: mapView,
          unit: "dual" // The scale bar displays both metric and non-metric units.
        });
        mapView.ui.add(scaleBar, "bottom-left");

        if(parentThis.siteId)
        {
          const markerSymbol = {
            type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
            url: "/assets/images/icon-flag.png",
            width: "24px",
            height: "24px",
            xoffset: "9px",
            yoffset: "10px"
          };

          const points = {
            type: "point", // autocasts as new Point()
            longitude: parentThis.longitude,
            latitude: parentThis.latitude
          };
          // Create a graphic and add the geometry and symbol to it
          const pointGraphic = new Graphic({
            geometry: points,
            symbol: markerSymbol
          });


          mapView.graphics.add(pointGraphic);
        }

        function createArea() {

          const circle = new Circle({
            center: [parentThis.longitude, parentThis.latitude],
            radius: parentThis.radius
          });
          const graphic = new Graphic({
            geometry: circle,
            symbol: {
              type: "simple-fill",
              outline: {
                color: [255, 0, 0],
                width: 2
              }
            }
          });

          mapView.graphics.add(graphic);
        }

        if (parentThis.id) {
          createArea();
        }

      });
    } catch (error) {
      console.log('We have an error: ' + error);
    }

  }

  ngOnInit() {
    this.setMapView();
    $(window).resize(()=> {
      this.setMapView();
    });
    if (!this.isGranted('A8_B22_C32_')) {
      if (this.isGranted('A8_B22_C33_')) {
        this.router.navigate(['/center/area/areaView']);
      }
    }
    this.area = new AreaDTO()
    this.getAllWarehouse();
    this.getSites();
    this.initializeMap();
    this.validateForm = this.fb.group({
      code: [null, [Validators.required, Validators.maxLength(255)]],
      warehouseId: [null, [Validators.nullValidator]],
      latitude: [null, [Validators.required]],
      longitude: [null, [Validators.required]],
      siteId: [null, Validators.required],
      // areaName: [ null, [ Validators.required ] ],
      radius: [null, [Validators.required]]
      //useType: [null, [Validators.required]],
    });

    this.checkStatusList = [
      { label: this.l('sealing_containers_area'), value: false, checked: false },
      { label: this.l('deblocking_area'), value: false, checked: false }];
  }
  setMapView(){
    const $mapview = $('.esri-view');
    $mapview.height($(window).innerHeight() - 240);
  }
  submitArea(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    this.checkStatusList.forEach(m => {
      if (m.checked == true) {
        if (m.label == this.l('sealing_containers_area')) {
          this.area.blockFlag = true;
        }
        if (m.label == this.l('deblocking_area')) {
          this.area.unblockFlag = true;
        }
      }
      else {
        if (m.label == this.l('sealing_containers_area')) {
          this.area.blockFlag = false;
        }
        if (m.label == this.l('deblocking_area')) {
          this.area.unblockFlag = false;
        }
      }
    })

    if (!this.area.unblockFlag && !this.area.blockFlag) {
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
      return;
    }

    if (this.validateForm.valid) { // 验证通过
      this._service.createAreaUsingPOST(this.area).subscribe(result => {
        if (result.success) {
          this.message.success(this.l('save_success'));
          this.area = result.result;
          this.initializeMap();
        }
        else {
          this.message.info(this.l(result.error.message));
        }
      }, error => {
        this.message.error(this.l(error.message));
      })

    } else { // 验证未通过
      this.message.error(this.l('verify_failed_please_check_the_form_item'));
    }
  }

  reset() {
    this.area = new AreaDTO();
    this.validateForm.reset();
  }

}
